<template>
  <div class="app-container">
    <div class="title-btns">
      <span class="role-span"><span></span>应用配置</span>
    </div>
    <!--表格渲染-->
    <el-row :gutter="15">
      <el-col :xs="24" :sm="24" :md="16" :lg="16" :xl="17">
        <el-card class="box-card" shadow="never">
          <div class="head-container">
            <div class="head-search">
              <!-- 搜索 -->
              <el-select v-model="query.type" clearable placeholder="查找类型" class="filter-item" style="width: 130px">
                <el-option v-for="item in queryTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
              </el-select>
              <el-input v-model="query.value" clearable placeholder="输入关键字搜索" style="width: 200px;" class="filter-item" @keyup.enter.native="toQuery" />
              <el-select v-model="query.status" clearable placeholder="状态" class="filter-item" style="width: 130px" @change="toQuery">
                <el-option v-for="item in dictobj['clients_status']" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
              <el-button class="filter-item" size="mini" type="primary" icon="el-icon-search" @click="toQuery">搜索</el-button>
              <el-button class="filter-item" size="mini" icon="el-icon-refresh" @click="toReSet">重置</el-button>
              <div style="float: right">
                <!-- 新增 -->
                <el-button v-permission="['ADMIN','CLIENTS_ALL','CLIENTS_CREATE']" class="filter-item" size="mini" type="primary" icon="el-icon-plus" @click="toAdd">新增</el-button>
              </div>
            </div>
            <!-- 导出 -->
            <el-table v-loading="loading" :data="data" size="small" style="width: 100%;" @current-change="handleCurrentChange">
              <el-table-column prop="clientId" label="应用标识" />
              <el-table-column :show-overflow-tooltip="true" prop="clientSecret" label="应用密钥" />
              <el-table-column prop="accessTokenValidity" label="token有效时间（mm）" />
              <el-table-column prop="refreshTokenValidity" label="refreshToken有效时间（mm）" />
              <el-table-column prop="scope" label="scope" />
              <el-table-column :show-overflow-tooltip="true" prop="webServerRedirectUri" label="回调地址" />
              <el-table-column :show-overflow-tooltip="true" prop="authorizedGrantTypes" label="oauth授权模式" />
              <el-table-column align="center" label="状态">
                <template slot-scope="scope">
                  <div v-for="item in dictobj['clients_status']" :key="item.id">
                    <template v-if="scope.row.status.toString() === item.value" :type="scope.row.status ? '' : 'info'">{{ item.label }}</template>
                  </div>
                </template>
              </el-table-column>
              <el-table-column v-if="checkPermission(['ADMIN','CLIENTS_ALL','CLIENTS_EDIT','CLIENTS_DELETE'])" label="操作" width="180" align="center">
                <template slot-scope="scope">
                  <el-button v-permission="['ADMIN','CLIENTS_ALL','CLIENTS_EDIT']" size="mini" type="text" @click="toUpdate(scope.row)">修改</el-button>
                  <el-popover
                    :ref="scope.row.id"
                    v-permission="['ADMIN','CLIENTS_ALL','CLIENTS_DELETE']"
                    placement="top"
                    width="180"
                  >
                    <p>确定删除本条数据吗？</p>
                    <div style="text-align: right; margin: 0">
                      <el-button size="mini" type="text" @click="$refs[scope.row.id].doClose()">取消</el-button>
                      <el-button :loading="delLoading" type="primary" size="mini" @click="subDelete(scope.row.id)">确定</el-button>
                    </div>
                    <el-button slot="reference" type="text" style="margin-left:10px" size="mini">删除</el-button>
                  </el-popover>
                </template>
              </el-table-column>
            </el-table>
            <!--分页组件-->
            <el-pagination
              :total="total"
              :current-page="page"
              style="margin-top: 8px;"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="sizeChange"
              @current-change="pageChange"
            />
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="7">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <el-tooltip class="item" effect="dark" content="选择指定应用配置服务" placement="top">
              <span class="role-span">服务配置</span>
            </el-tooltip>
            <div style="float: right">
              <el-button
                v-permission="['ADMIN','CLIENTS_ALL','CLIENTS_EDIT']"
                :loading="servicesLoading"
                icon="el-icon-check"
                size="mini"
                type="primary"
                @click="saveServices"
              >保存</el-button>
            </div>

          </div>
          <el-tree
            ref="service"
            :data="services"
            :default-checked-keys="servicesIds"
            :props="defaultProps"
            show-checkbox
            accordion
            node-key="id"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- </el-col>
    </el-row>-->
    <eForm ref="form" :is-add="isAdd" :dictobj="dictobj" />
  </div>
</template>

<script>
import checkPermission from '@/utils/permission'
import initData from '@/mixins/initData'
import initDict from '@/mixins/initDict'
import { del, get, editServices } from '@/api/auth/clients'
import { tree } from '@/api/auth/service'
import { parseTime } from '@/utils/index'
import eForm from './module/form'
export default {
  components: { eForm },
  mixins: [initData, initDict],
  data() {
    return {
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      queryTypeOptions: [
        { key: 'clientId', display_name: '应用标识' },
        { key: 'authorizedGrantTypes', display_name: '授权类型' }
      ],
      delLoading: false, sup_this: this, servicesLoading: false, currentId: null,
      dictobj: {},
      services: [],
      servicesIds: []

    }
  },
  created() {
    this.getServices()

    this.$nextTick(() => {
      this.getDictObj('clients_status')
      this.init()
    })
  },
  methods: {
    parseTime,
    checkPermission,
    beforeInit() {
      this.$refs.service.setCheckedKeys([])
      this.url = 'oauth/clients'
      const sort = 'id desc'
      const query = this.query
      const type = query.type
      const value = query.value
      const status = query.status
      this.params = { page: this.page, size: this.size, sort: sort }
      if (type && value) {
        this.params[type] = value
      }
      if (status !== '' && status !== null) {
        this.params['status'] = status
      }
      return true
    },

    /**
 * 去增加
 */
    toAdd() {
      this.isAdd = true
      this.$refs.form.resetForm()
      this.$refs.form.dialog = true
    },
    toUpdate(data) {
      this.isAdd = false
      const _this = this.$refs.form
      _this.form = { id: data.id, clientId: data.clientId, clientSecretStr: data.clientSecretStr, status: data.status.toString(),
        scope: data.scope, webServerRedirectUri: data.webServerRedirectUri, authorizedGrantTypes: data.authorizedGrantTypes,
        accessTokenValidity: data.accessTokenValidity, refreshTokenValidity: data.refreshTokenValidity }
      _this.dialog = true
    },
    // 点击应用行
    handleCurrentChange(val) {
      if (val) {
        this.currentId = val.id
        get(val.id).then(res => {
          this.servicesIds = res.data.client.servicesIds
          this.$refs.service.setCheckedKeys(this.servicesIds)
        }).catch(err => {
          console.log(err.response.data.res_msg)
        })
      }
    },
    // 删除应用
    subDelete(id) {
      this.delLoading = true
      del(id).then(res => {
        this.delLoading = false
        this.$refs[id].doClose()
        this.dleChangePage()
        this.init()
        this.$notify({
          title: '删除成功',
          type: 'success',
          duration: 2500
        })
      }).catch(err => {
        console.log(err.response.data.res_msg)
      })
    },

    // 获取服务树形数据
    getServices() {
      tree().then(res => {
        this.services = res.data.tree
      })
    },
    // 提交关联的服务
    saveServices() {
      this.servicesLoading = true
      const client = { id: this.currentId, servicesIds: [] }
      this.$refs.service.getCheckedKeys().forEach(function(data, index) {
        client.servicesIds.push(data)
      })
      editServices(client).then(res => {
        this.$notify({
          title: '保存成功',
          type: 'success',
          duration: 2500
        })
        this.servicesLoading = false
      }).catch(err => {
        this.servicesLoading = false
        this.$notify({
          title: err.response.data.res_msg,
          type: 'error',
          duration: 2500
        })
        console.log(err.response.data.res_msg)
      })
    }

  }
}
</script>

<style scoped lang="scss">

</style>
